<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" class="half-tabs" @tab-click="getList">
      <el-tab-pane label="即将到期" name="expiring">
        <el-table v-loading="loading" :data="expiringList" style="width: 100%">
          <el-table-column label="食材名称" align="center" prop="name" />
          <el-table-column
            label="生产日期"
            align="center"
            prop="productionDate"
            width="180"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.productionDate, "{y}-{m}-{d}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="到期日期"
            align="center"
            prop="expireDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="保质天数" align="center">
            <template #default="scope">
              <div style="color: red;">
                {{ scope.row.daysRemaining }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="图片"
            align="center"
            prop="imageUrl"
            width="100"
          >
            <template #default="scope">
              <image-preview
                :src="scope.row.imageUrl"
                :width="50"
                :height="50"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="上传时间"
            align="center"
            prop="uploadTime"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.uploadTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="expiringTotal"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>

      <el-tab-pane label="所有食材" name="all">
        <el-table
          v-loading="loading"
          :data="foodPurchaseList"
          style="width: 100%"
        >
          <el-table-column label="食材名称" align="center" prop="name" />
          <el-table-column
            label="生产日期"
            align="center"
            prop="productionDate"
            width="180"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.productionDate, "{y}-{m}-{d}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="到期日期"
            align="center"
            prop="expireDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="保质天数"
            align="center"
            prop="daysRemaining"
          >
            <template #default="scope">
    <!-- scope.row 表示当前行的数据对象 -->
    <span 
      :style="{ 
        color: scope.row.daysRemaining <= 0 ? 'red' : 'green',
        fontWeight: scope.row.daysRemaining <= 3 ? 'bold' : 'normal'
      }"
    >
      <!-- 根据剩余天数显示不同文本 -->
      {{ 
        scope.row.daysRemaining > 0 
          ? `剩余 ${scope.row.daysRemaining} 天` 
          : scope.row.daysRemaining === 0 
            ? '今日过期' 
            : `已过期 ${-scope.row.daysRemaining} 天` 
      }}
    </span>
  </template>
        </el-table-column>
          <el-table-column
            label="图片"
            align="center"
            prop="imageUrl"
            width="100"
          >
            <template #default="scope">
              <image-preview
                :src="scope.row.imageUrl"
                :width="50"
                :height="50"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="上传时间"
            align="center"
            prop="uploadTime"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.uploadTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { listFoodPurchase } from "@/api/kindergarten/foodPurchase";

const { proxy } = getCurrentInstance();
const loading = ref(true);
const total = ref(0);
const activeTab = ref("expiring");
const foodPurchaseList = ref([]);
const expiringList = ref([]);
const expiringTotal=ref(0)

const data = reactive({
  queryParams: { pageNum: 1, pageSize: 10 },
});
const { queryParams } = toRefs(data);

// 计算保质天数
function calcDaysRemaining(expireDate) {
  if (!expireDate) return 0;
  const now = new Date().getTime();               
  const expireTime = new Date(expireDate).getTime(); 
  return Math.ceil((expireTime - now) / (24 * 60 * 60 * 1000)); 
}

const socket = new WebSocket("ws://192.168.1.103/ws")

socket.onopen =()=>{
  console.log('连接成功');
  
}
socket.onmessage = (event)=>{
    console.log(event.data);
    mengon(event.data)
}
socket.onclose = (event)=>{
  console.log('WebSocket 连接已关闭', event);

}
socket.onerror = (error) => {
  console.error('WebSocket 错误:', error);
  console.error('错误名称:', error.name);
  console.error('错误消息:', error.message);
};

const mengon = (data)=>{
  const datas = JSON.parse(data)
  foodPurchaseList.value.unshift(datas)
}

// 获取列表
function getList() {
  loading.value = true;
  listFoodPurchase(queryParams.value).then((res) => {
    const rows = res.rows.map((item) => ({
      ...item,
      daysRemaining: calcDaysRemaining(item.expireDate),
    }));

    foodPurchaseList.value = rows;
    expiringList.value = rows.filter((r) =>r.state==2);
    // console.log(expiringList.value);
    expiringTotal.value=expiringList.value.length
    
    
    total.value = res.total;
    loading.value = false;
  });
}

getList();
</script>

<style scoped>
.half-tabs ::v-deep(.el-tabs__nav) {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.half-tabs ::v-deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  border-right: 1px solid #ebeef5;
}

/* 去掉最后一个右边框 */
.half-tabs ::v-deep(.el-tabs__item:last-child) {
  border-right: none;
}
</style>
